package cn.jingyuan.bee.utils.text.escape;

import cn.jingyuan.bee.utils.CharUtils;
import cn.jingyuan.bee.utils.text.StringsBuilder;
import cn.jingyuan.bee.utils.text.replacer.StringReplacer;

/**
 * 形如 &#39; 的反转义器
 */
public class NumericEntityUnescaper extends StringReplacer {

    @Override
    protected int replace(CharSequence string, int pos, StringsBuilder out) {
        final int len = string.length();
        // 检查以确保以&#开头
        if (string.charAt(pos) == '&' && pos < len - 2 && string.charAt(pos + 1) == '#') {
            int start = pos + 2;
            boolean isHex = false;
            final char firstChar = string.charAt(start);
            if (firstChar == 'x' || firstChar == 'X') {
                start++;
                isHex = true;
            }

            // 确保&#后还有数字
            if (start == len) {
                return 0;
            }

            int end = start;
            while (end < len && CharUtils.isHexChar(string.charAt(end))) {
                end++;
            }
            final boolean isSemiNext = (end != len) && (string.charAt(end) == ';');
            if (isSemiNext) {
                int entityValue;
                try {
                    if (isHex) {
                        entityValue = Integer.parseInt(string.subSequence(start, end).toString(), 16);
                    } else {
                        entityValue = Integer.parseInt(string.subSequence(start, end).toString(), 10);
                    }
                } catch (final NumberFormatException nfe) {
                    return 0;
                }
                out.append((char) entityValue);
                return 2 + end - start + (isHex ? 1 : 0) + (isSemiNext ? 1 : 0);
            }
        }
        return 0;
    }

}
